package org.windey.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 
 * connectie leggen naar de server
 *
 */
public class WindeyServerConnection
{
	/**
	 * de socket om de verbinding te leggen
	 */
	private Socket connectSocket ;
	/**
	 * bijhouden of er connectie is of niet
	 */
	private boolean connected;
	/**
	 * de settings die op de computer zijn opgeslagen
	 */
	private WindeySettings settings;
	/**
	 * inkomende data
	 */
	private BufferedReader in;
	/**
	 * uitgaande data
	 */
	private PrintWriter out;
	
	public WindeyServerConnection(WindeySettings settings)
	{
		this.settings = settings;
		this.connected = false;
	}
	
	/**
	 * om connectie naar de server te leggen
	 * @throws WindeyServerConnectionException als connectie niet slaagt
	 */
	public void connect() throws WindeyServerConnectionException
	{
		try
		{
			connectSocket = new Socket(settings.getHostname(), settings.getPort());
			in = new BufferedReader(new InputStreamReader(connectSocket.getInputStream()));
			out = new PrintWriter(connectSocket.getOutputStream(), true);
			connected = true;
		}
		catch (NumberFormatException e)
		{
			e.printStackTrace();
			throw new WindeyServerConnectionException();
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
			throw new WindeyServerConnectionException();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			throw new WindeyServerConnectionException();
		}
	}

	/**
	 * om de connectie te sluiten
	 * @throws WindeyServerConnectionException als de disconnectie niet gaat
	 */
	public void disconnect() throws WindeyServerConnectionException
	{
		try
		{
			if (connectSocket != null)
			{
				send("EOC") ;
				connectSocket.close();
				connected = false;
			}
		} 
		catch (IOException e)
		{
			e.printStackTrace();
			throw new WindeyServerConnectionException();
		}	
	}
	
	/**
	 * geeft de status van de connectie terug
	 * @return true: connectie is er, false: er is geen connectie
	 */
	public boolean isConnected()
	{
		return this.connected;
	}
	
	/**
	 * om data te versturen
	 * @param data de te versturen data
	 */
	public void send(String data)
	{
		out.println(data);
	}
	
	/**
	 * wanneer data wordt ontvangen
	 * @return de ontvangen data
	 */
	public String receive()
	{
		String result;
		try
		{
			result = in.readLine();
		}
		catch (IOException e)
		{
			result = "";
			e.printStackTrace();
		}
		return result;
	}
}
